package com.joymedia.thor.page;


import java.util.Objects;

/**
 * @author XSH
 */
public class PageRequest extends AbstractPageRequest {

    private final Sort sort;

    protected PageRequest(int page, int size, Sort sort) {
        super(page, size);
        if (Objects.isNull(sort)) {
            throw new NullPointerException("Sort must not be null!");
        }
        this.sort = sort;
    }

    public static PageRequest of(int page, int size) {
        return of(page, size);
    }

    public static PageRequest of(int page, int size, Sort sort) {
        return new PageRequest(page, size, sort);
    }

    public static PageRequest of(int page, int size, String property, Sort.Direction direction) {
        return of(page, size, Sort.by(property, direction));
    }

    public Sort getSort() {
        return sort;
    }

    @Override
    public Pageable next() {
        return new PageRequest(getPageNumber() + 1, getPageSize(), getSort());
    }

    @Override
    public PageRequest previous() {
        return getPageNumber() == 0 ? this : new PageRequest(getPageNumber() - 1, getPageSize(), getSort());
    }

    @Override
    public Pageable first() {
        return new PageRequest(0, getPageSize(), getSort());
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof PageRequest)) {
            return false;
        }

        PageRequest that = (PageRequest) obj;
        return super.equals(that) && this.sort.equals(that.sort);
    }

    @Override
    public int hashCode() {
        return 31 * super.hashCode() + sort.hashCode();
    }

    @Override
    public String toString() {
        return String.format("Page request [number: %d, size %d, sort: %s]", getPageNumber(), getPageSize(), sort);
    }
}
